package com.huike.contract.service.impl;

import com.huike.business.mapper.TbBusinessMapper;
import com.huike.clues.domain.SysUser;
import com.huike.clues.domain.TbAssignRecord;
import com.huike.clues.domain.TbClue;
import com.huike.clues.domain.TbRulePool;
import com.huike.clues.mapper.SysUserMapper;
import com.huike.clues.mapper.TbAssignRecordMapper;
import com.huike.clues.mapper.TbClueMapper;
import com.huike.clues.service.ISysUserService;
import com.huike.clues.service.TbRulePoolService;
import com.huike.clues.utils.HuiKeCrmDateUtils;
import com.huike.common.constant.Constants;
import com.huike.common.core.domain.entity.SysUserDTO;
import com.huike.common.utils.DateUtils;
import com.huike.contract.domain.vo.TransferVo;
import com.huike.contract.service.TransferService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
@Service
public class TransferServiceImpl implements TransferService {
    @Resource
    private ISysUserService userService;

    @Resource
    private TbAssignRecordMapper assignRecordMapper;

    @Resource
    private TbRulePoolService rulePoolService;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private TbClueMapper clueMapper;


    @Resource
    private TbBusinessMapper businessMapper;


    @Override
    public List<TransferVo> selectTransferList(SysUserDTO userDTO) {
        // 创建一个TransferVo类型的列表
        List<TransferVo> transfervoList =new ArrayList<>();
        // 调用userService的selectUserList方法，获取用户列表
        List<SysUserDTO> list = userService.selectUserList(userDTO);
        // 遍历用户列表
        for (SysUserDTO sysUserDTO : list) {
            // 创建一个TransferVo类型的对象
            TransferVo transfervo= new TransferVo();
            // 调用assignRecordMapper的countAssignCluesByUser方法，获取用户 clue 数
            int clueNum= assignRecordMapper.countAssignCluesByUser(sysUserDTO.getUserId());
            // 调用assignRecordMapper的countAssignBusinessByUser方法，获取用户 business 数
            int businessNum= assignRecordMapper.countAssignBusinessByUser(sysUserDTO.getUserId());
            // 如果 clue 数或者 business 数大于 0
            if(clueNum+businessNum>0){
                // 设置 TransferVo 对象的用户名
                transfervo.setUserName(sysUserDTO.getUserName());
                // 设置 TransferVo 对象 clue 数
                transfervo.setClueNum(clueNum);
                // 设置 TransferVo 对象 business 数
                transfervo.setBusinessNum(businessNum);
                // 设置 TransferVo 对象用户 id
                transfervo.setUserId(sysUserDTO.getUserId());
                // 设置 TransferVo 对象电话号码
                transfervo.setPhonenumber(sysUserDTO.getPhonenumber());
                // 设置 TransferVo 对象创建时间
                transfervo.setCreateTime(sysUserDTO.getCreateTime());
                // 将 TransferVo 对象添加到 transfervoList 中
                transfervoList.add(transfervo);
            }
        }
        return transfervoList;
    }

    @Override
    //根据用户ID和类型，获取转派记录
    public Map<String,Object> assignment(String type, Long userId, Long transferUserId) {
        Map<String ,Object> result =new HashMap<>();
        if (TbAssignRecord.RecordType.CLUES.getValue().equals(type)) {
            //获取当前用户ID的线索数量
            int clueNum = assignRecordMapper.countAssignCluesByUser(userId);
            //如果当前用户ID的线索数量大于等于0
            if (clueNum >= 0) {
                //获取线索规则池
                TbRulePool rulePool = rulePoolService.selectTbRulePoolByType(Constants.rule_type_clue);
                //获取被转派人的线索数量
                int transferUserClueNum = assignRecordMapper.countAssignCluesByUser(transferUserId);
                // 被转派人保有量达到最大值
                //如果被转派人的线索数量达到最大值
                if (transferUserClueNum >= rulePool.getMaxNunmber()) {
                    //返回失败信息
                    result.put("flag",false);
                    result.put("msg","线索转换失败！已经达到被转派人最大保有量");
                } else {
                    //创建转派记录
                    TbAssignRecord assignRecord = new TbAssignRecord();
                    assignRecord.setUserId(userId);
                    assignRecord.setLatest("1");
                    assignRecord.setType(TbAssignRecord.RecordType.CLUES.getValue());
                    //查询当前用户ID的转派记录
                    List<TbAssignRecord> list = assignRecordMapper.selectAssignRecordList(assignRecord);
                    //遍历转派记录
                    for (int i = 0; i < list.size(); i++) {
                        TbAssignRecord tbAssignRecord = list.get(i);
                        //获取被转派人的用户信息
                        SysUserDTO sysUserDTO = sysUserMapper.selectUserById(transferUserId);
                        tbAssignRecord.setUserId(transferUserId);
                        tbAssignRecord.setUserName(sysUserDTO.getUserName());
                        tbAssignRecord.setDeptId(sysUserDTO.getDeptId());
                        tbAssignRecord.setCreateTime(DateUtils.getNowDate());
                        //更新转派记录
                        assignRecordMapper.updateAssignRecord(tbAssignRecord);
                        //设置线索的状态为待跟进
                        clueMapper.setTransfer(tbAssignRecord.getAssignId(), TbClue.StatusType.UNFOLLOWED.getValue());
                        //根据规则获取分配记录的结束时间
                        Date endDate = HuiKeCrmDateUtils.getEndDateByRule(tbAssignRecord);
                        //更新线索的失效时间
                        clueMapper.updateClueEndTimeById(tbAssignRecord.getAssignId(),endDate);
                        //如果被转派人的线索数量达到最大值
                        if (transferUserClueNum + i >= rulePool.getMaxNunmber()) {
                            //返回失败信息
                            result.put("flag",false);
                            result.put("msg","线索转换失败！已经分配" + i + " 线索");
                            break;
                        }
                    }
                }
            }
        }
        if (TbAssignRecord.RecordType.BUSNIESS.getValue().equals(type)) {
            //获取当前用户ID的商机数量
            int busniessNum = assignRecordMapper.countAssignBusinessByUser(userId);
            //如果当前用户ID的商机数量大于等于0
            if (busniessNum >= 0) {
                //获取商机规则池
                TbRulePool rulePool = rulePoolService.selectTbRulePoolByType(Constants.rule_type_business);
                //获取被转派人的商机数量
                int transferUserBusinessNum = assignRecordMapper.countAssignBusinessByUser(transferUserId);
                //被转派人保有量达到最大值
                //如果被转派人的商机数量达到最大值
                if (transferUserBusinessNum >= rulePool.getMaxNunmber()) {
                    //返回失败信息
                    result.put("flag",false);
                    result.put("msg","线索转换失败！已经达到被转派人最大保有量");
                } else {
                    //创建转派记录
                    TbAssignRecord assignRecord = new TbAssignRecord();
                    assignRecord.setUserId(userId);
                    assignRecord.setLatest("1");
                    assignRecord.setType(TbAssignRecord.RecordType.BUSNIESS.getValue());
                    //查询当前用户ID的转派记录
                    List<TbAssignRecord> list = assignRecordMapper.selectAssignRecordList(assignRecord);
                    //遍历转派记录
                    for (int i = 0; i < list.size(); i++) {
                        TbAssignRecord tbAssignRecord = list.get(i);
                        //获取被转派人的用户信息
                        SysUserDTO sysUserDTO = sysUserMapper.selectUserById(transferUserId);
                        tbAssignRecord.setUserId(transferUserId);
                        tbAssignRecord.setUserName(sysUserDTO.getUserName());
                        tbAssignRecord.setDeptId(sysUserDTO.getDeptId());
                        tbAssignRecord.setCreateTime(DateUtils.getNowDate());
                        //更新转派记录
                        assignRecordMapper.updateAssignRecord(tbAssignRecord);
                        //根据规则获取分配记录的结束时间
                        Date endDate = HuiKeCrmDateUtils.getEndDateByRule(tbAssignRecord);
                        //更新商机的回收时间
                        businessMapper.updateBusinessEndTimeById(tbAssignRecord.getAssignId(),endDate);
                        //如果被转派人的商机数量达到最大值
                        if (transferUserBusinessNum + i >= rulePool.getMaxNunmber()) {
                            //返回失败信息
                            result.put("flag",false);
                            result.put("msg","商机转换失败！已经转派" + i + " 商机");
                            break;
                        }
                    }
                }
            }
        }
        return result;
    }
}
